﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CCF20Model;
using System.ServiceModel;
using System.Windows;
using CCF20Model.FaultHandler;
using System.Globalization;
using WiseLink.RDS.Resource;
using System.Web.Script.Serialization;

namespace ZICMonitor
{


    partial class ZICModel
    {
        private LoginInfo login = null;
        private VehicleModel vehicleModel;
        private FaultModel faultModel;
        private StatsModel statsModel;
        JavaScriptSerializer jsonSerializer;

        private static bool isInitialized = false;


        public ZICModel(ModelFactory modelFactory)
        {
            modelFactory = new ModelFactory();
            vehicleModel = (VehicleModel)modelFactory.CreateModel(ModelName.VehicleModel);
            faultModel = (FaultModel)modelFactory.CreateModel(ModelName.FaultModel);

            jsonSerializer = new JavaScriptSerializer();
            statsModel = new StatsModel();
        
            login = faultModel.GetLoginInfo();
        }
        
        public void GetDeviceRecord()
        {

            int maxID = faultModel.GetAnchiID();
            

            string strReturn = ZICBase.ExectueMethod(ZICMethod.GetDeviceRecord, new object[] { string.Empty, string.Empty, maxID });
            
            if (strReturn == null) return;
            List<CarRecordSend> list;
            try
            {
                
                list = jsonSerializer.Deserialize <List<CarRecordSend>>(strReturn);
            }
            catch
            {
                LoggerHelper.LogZICMonitor(string.Format("[GetDeviceRecord ZIC return bad value] {0}", strReturn));
                return;
            }
            if (list.Count > 0)
            {
                LoggerHelper.LogZICMonitor(string.Format("GetDeviceRecord: IDSName:{0}\tIDSPwd:{1}\tMaxID:{2}\tCount:{3}", login.IDSName, login.IDSPassword, maxID, list.Count));
            }

            foreach (CarRecordSend record in list)
            {
                Fault f = new Fault();
                f.IsActive = true;
                f.IsConfirmed = false;
                f.AnchiID = record.AnchiId;
                f.HappenDate = Convert.ToDateTime(record.CreateTime);
                f.IDCSimNumber = record.DeviceId.Trim();
                f.CurrentMileage = record.Distance;
                f.Code = record.TroubleCodeId.Trim();
                f.CodeDescription = record.Desc.Trim();
                f.CodeType = record.DisplayOrder.Trim();
                f.IsSMSed = false;
                f.IDSID = Convert.ToInt32(record.ids);
                f.Priority = (short) (f.CodeType.Equals("严重") ? 1 : 5);
                short tempCodeVersion = 0;
                if (short.TryParse(record.TroubleContent, out tempCodeVersion))
                {
                    f.CodeVersion = tempCodeVersion;
                }
                else
                {
                    f.CodeVersion = 1;
                }
                f.ReceiveDate = DateTime.Now;
                bool tempIsNormalFault;
                if (bool.TryParse(record.Ex, out tempIsNormalFault) && tempIsNormalFault)
                {
                    f.IsNormalFault = tempIsNormalFault;
                }
                else
                {
                    f.IsNormalFault = false;
                }
                f.FaultInfo = record.Excontent;
                if (DateTime.Now > DateTime.Parse(DateTime.Now.ToShortDateString() + " 17:30:00"))
                {
                    //如果收到的故障时间是在17：30后，则以第二天的9：00 作为有效的计算时间
                    f.EffectiveReceiveDate = DateTime.Parse((DateTime.Now + TimeSpan.FromDays(1)).ToShortDateString() + " 9:00:00");
                }
                else
                {
                    f.EffectiveReceiveDate = DateTime.Now;
                }
                if (record.TroubleCodeId.Length > 0)
                {
                    f.FaultType = WiseLinkRDSStatus.Fault_Type_Fault;

                }
                else
                {
                    f.FaultType = WiseLinkRDSStatus.Fault_Type_Maintenance;
                }

                IFaultHandler faultHandler = new FindVehicleByFaultHandler2(f, new CCF20Entities());
                faultHandler.ProcessRequest();
            }

        }

        public void GetCrash()
        {
            DateTime lastCrashTime = faultModel.GetLastCrashTime();
            // if there is no crash record in db, pick the crash from 3 days ago.
            //if (lastCrashTime == null) lastCrashTime = DateTime.Now - new TimeSpan(3, 0, 0, 0);
            //DateTime lastCrashTime = new DateTime(2011,1,1);

            string strReturn = ZICBase.ExectueMethod(ZICMethod.GetCrash, new object[] { string.Empty,string.Empty, lastCrashTime });
            
            if (strReturn == null) return;

            List<CrashModel> list;
            try
            {
                
                list = jsonSerializer.Deserialize<List<CrashModel>>(strReturn);
                
            }
            catch
            {
                LoggerHelper.LogZICMonitor(string.Format("[GetCrash ZIC return bad value] {0}", strReturn));
                return;
            }
            if (list.Count > 0)
            {
                LoggerHelper.LogZICMonitor(string.Format("GetCrash: IDSName:{0}\tIDSPwd:{1}\tMaxID:{2}\tCount:{3}", login.IDSName, login.IDSPassword, lastCrashTime, list.Count));
            }
            foreach (CrashModel record in list)
            {
                Fault f = new Fault();
                f.HappenDate = Convert.ToDateTime(record.CrashTime);
                f.ReceiveDate = DateTime.Now;
                f.EffectiveReceiveDate = DateTime.Now;
                f.IDCSimNumber = record.Idc.Trim();
                f.AnchiID = record.Id;
                f.IsActive = true;
                f.IsConfirmed = false;
                f.FaultType = WiseLinkRDSStatus.Fault_Type_Urgent;
                f.IDSID = Convert.ToInt32(record.ids);

                IFaultHandler faultHandler = new FindVehicleByFaultHandler2(f, new CCF20Entities());
                faultHandler.ProcessRequest();
            }
        }
        public void UploadDayStats()
        {
            IList<DailyStats> dayInfo = statsModel.GetDailyStats();
            dayinfoModel zicDayInfo = new dayinfoModel();
            zicDayInfo.IDS = login.IDSName;
            zicDayInfo.Pwd = login.IDSPassword;
            zicDayInfo.StatisticsTime = DateTime.Now.ToLongDateString();
            foreach (DailyStats dayStat in dayInfo)
            {
                if (dayStat.Name1 == "当日注册套数")
                {
                    zicDayInfo.register_idc = dayStat.Value1;
                }
                else if (dayStat.Name1 == "当日事故车报警且有人关怀的总数")
                {
                    zicDayInfo.alarm_idc = dayStat.Value1 + dayStat.Value2;
                }
                else if (dayStat.Name1 == "当日有故障且有客户关怀IDC的总数")
                {
                    zicDayInfo.trouble_idc = dayStat.Value1 + dayStat.Value2;
                    zicDayInfo.conservation_trouble_care_idc = dayStat.Value1;
                    zicDayInfo.conservation_trouble_nocare_idc = dayStat.Value2;
                }
                else if (dayStat.Name1 == "当日有需要保养且有客户关怀IDC的总数")
                {
                    zicDayInfo.conservation_care_idc = dayStat.Value1;
                    zicDayInfo.conservation_nocare_idc = dayStat.Value2;
                }
                else if (dayStat.Name1 == "当日拒绝回场的客户数量")
                {
                    zicDayInfo.noback_idc = dayStat.Value1;
                }



            }
            if (ZICMonitorModel.IsJava)
            {
                ZICBase.ExectueMethod(ZICMethod.UpLoadDayInfo, new object[] { jsonSerializer.Serialize(zicDayInfo) });
            }
            LoggerHelper.LogZICMonitor("Complete UploadDayStats Count=" + dayInfo.Count);

        }
        public void UpdateZICInfo(bool IsAvailable)
        {
            faultModel.UpdateZICInfo(DateTime.Now, IsAvailable);
        }
        public void UploadDailyFaultStatsByVehicleTypeStats()
        {
            IList<FaultStatsByVehicleType> FaultsStat = statsModel.GetDailyFaultStatsByVehicleType();
            foreach (FaultStatsByVehicleType faultStat in FaultsStat)
            {
                daycartypeModel carModel = new daycartypeModel();
                carModel.carmodel = faultStat.Model;
                carModel.Troubletype = faultStat.MyFaultType;
                carModel.IDCCOUNT = faultStat.IDCCount;
                carModel.IDS = login.IDSName;
                carModel.StatisticsTime = DateTime.Now.ToLongDateString();
                JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
                
             
                
                if (ZICMonitorModel.IsJava)
                {
                    ZICBase.ExectueMethod(ZICMethod.UpLoadDayTyInfo, new object[]{
                                            login.IDSName,
                                            login.IDSPassword,
                                            jsonSerializer.Serialize(carModel)});
                }

            }
            LoggerHelper.LogZICMonitor("Complete UploadDailyFaultStatsByVehicleTypeStats Count=" + FaultsStat.Count);
        }
        public void UploadDailyCareStats()
        {
            IEnumerable<CareStat> CareStats = statsModel.GetDailyCareStats();
            foreach (CareStat careStat in CareStats)
            {
                ServerTjRecordModel serverTJModel = new ServerTjRecordModel();
                serverTJModel.Anchitime = careStat.ReceiveDate.GetValueOrDefault().ToLongDateString();
                //serverTJModel.Createmonth = new DateTime(DateTime.Now.Year,
                //                                            DateTime.Now.Month,
                //                                            DateTime.Now.Day);
                serverTJModel.Createmonth = DateTime.Now.ToLongDateString();
                //serverTJModel.CreateTime = DateTime.Now;
                serverTJModel.CreateTime = DateTime.Now.ToLongDateString();
                serverTJModel.Fun = careStat.MyScore;
                serverTJModel.Idc = careStat.IDCSimNumber;
                serverTJModel.Ids = Convert.ToInt16(login.IDSName);
                //serverTJModel.Tracetime = careStat.FirstContactDate;
                serverTJModel.Tracetime = careStat.FirstContactDate.GetValueOrDefault().ToLongDateString();
                if (careStat.FaultType == WiseLinkRDSStatus.Fault_Type_Fault)
                {
                    
                        serverTJModel.Type = 1;
                }else if (careStat.FaultType == WiseLinkRDSStatus.Fault_Type_Maintenance)
                {
                        serverTJModel.Type = 2;
                }else if (careStat.FaultType == WiseLinkRDSStatus.Fault_Type_Urgent)
                {
                        serverTJModel.Type = 0;
                }

                if (ZICMonitorModel.IsJava)
                {
                    
                                            
                     ZICBase.ExectueMethod(ZICMethod.AddServerTjRecord, new object[]{
                                            login.IDSName,
                                            login.IDSPassword,
                                            jsonSerializer.Serialize(serverTJModel)});
                
                }
            }
            LoggerHelper.LogZICMonitor("Complete UploadDailyCareStats Count=" + CareStats.Count());
        }
        public void UploadDailyDeclineStatsByVehicleType()
        {
            IEnumerable<DeclineStatsByVehicleType> DeclineStats = statsModel.GetDailyDelicneStatsByVehicleType();
            foreach (DeclineStatsByVehicleType declineStats in DeclineStats)
            {
                JavaDeclineStatsByVehicleType javaType = new JavaDeclineStatsByVehicleType();
                javaType.Buytime = declineStats.Buytime.GetValueOrDefault().ToLongDateString();
                javaType.Createtime = declineStats.Createtime.GetValueOrDefault().ToLongDateString();
                javaType.Jjcontent = declineStats.Jjcontent;
                javaType.Jjtype = declineStats.Jjtype;
                javaType.TyID = declineStats.TyID;

                if (ZICMonitorModel.IsJava)
                {
                    ZICBase.ExectueMethod(ZICMethod.AddTbnobacktj, new object[]{
                                        login.IDSName,
                                        login.IDSPassword,
                                        jsonSerializer.Serialize(javaType)});
                }
            }
            LoggerHelper.LogZICMonitor("Complete UploadDailyDeclineStatsByVehicleType Count=" + DeclineStats.Count());
        }
        public void GetDeviceStatus()
        {
            string ret;
            //bool updateSuccess = true;
            DateTime lastRequestDate = (DateTime)vehicleModel.GetZICLastResponseID(ZICResponseCategory.GetDeviceStatus);
            if (ZICMonitorModel.IsJava)
            {
                ret = ZICBase.ExectueMethod(ZICMethod.GetDeviceStatu, new object[]{
                                                             login.IDSName,
                                                             login.IDSPassword,
                                                             lastRequestDate});


                LoggerHelper.LogZICMonitor(string.Format("GetDeviceStatu: IDSName:{0}\tIDSPwd:{1}\tMaxID:{2}", login.IDSName, login.IDSPassword, lastRequestDate));
                if (ret == null)
                {
                    return;
                }
                List<DeviceStatu> list = jsonSerializer.Deserialize<List<DeviceStatu>>(ret);

                if (list == null)
                {
                    return;
                }

                LoggerHelper.LogZICMonitor(string.Format("GetDeviceStatu: IDSName:{0}\tIDSPwd:{1}\tMaxID:{2}\tCount:{3}", login.IDSName, login.IDSPassword, lastRequestDate, list.Count));

                foreach (DeviceStatu record in list)
                {
                    if (!vehicleModel.UpdateDeviceUsageStatus(record.idc, record.statu == 1 ? "可用" : "不可用"))
                    {
                        //updateSuccess = false; //只有全部设备都跟新，才会将时间前移。为了防止设备没有在CCF中事先输入
                        LoggerHelper.LogZICDebug(string.Format("[获取设备状态]GetDeviceStatu: IDC={0} 可用={1}", record.idc, record.statu));
                    }
                }
                //if (updateSuccess)
                //{
                vehicleModel.UpdateZICLastResponseID(ZICResponseCategory.GetDeviceStatus);
                //}

            }
        }
        public void GetDefectedProduct()
        {
            string ret;
            if (ZICMonitorModel.IsJava)
            {
                ret = ZICBase.ExectueMethod(ZICMethod.GetTrobuleDevice, new object[]{ login.IDSName, login.IDSPassword});

                LoggerHelper.LogZICMonitor(string.Format("GetTrobuleDevice: IDSName:{0}\tIDSPwd:{1}", login.IDSName, login.IDSPassword));
                if (ret == null)
                {
                    return;
                }
                List<DefectedProduct> list = jsonSerializer.Deserialize<List<DefectedProduct>>(ret);
                if (list == null)
                {
                    return;
                }

                LoggerHelper.LogZICMonitor(string.Format("GetTrobuleDevice: Count:{0}", list.Count));
                foreach (DefectedProduct record in list)
                {
                    vehicleModel.AddDefectedProduct(record.idc.Trim());
                    LoggerHelper.LogZICDebug(string.Format("[获取无心跳的设备]GetTrobuleDevice: IDC={0} ", record.idc));
                }

            }
        }


        public void SendManagerReportSMS()
        {
            GeneralStatu status = ProfileModel.GetGeneralStatus("管理信息每日汇报");
            DateTime mangerReportTime = DateTime.Today + new TimeSpan(17, 30, 0);
            DateTime currentManagerReportTime = new DateTime(2000, 1, 1);
            if (status.StatusValue != null)
            {
                CultureInfo culture = CultureInfo.CreateSpecificCulture("zh-CHS");

                if (!DateTime.TryParse(status.StatusValue,
                                        culture,
                                        DateTimeStyles.None,
                                        out currentManagerReportTime))
                {
                    throw new Exception(string.Format("[SendManagerReportSMS] Can't covnert datetime {0}", status.StatusValue));
                }

            }
            if (status.StatusValue == null || DateTime.Now.Subtract(currentManagerReportTime).TotalDays >= 1)
            {
                if (DateTime.Now.Subtract(mangerReportTime).TotalMinutes > 0)
                {
                    CCF20Entities ccf20 = new CCF20Entities();
                    SMSTest smsTest = new SMSTest(ccf20);
                    
                    smsTest.ScheduleManagerReportSMS();
                    //status.StatusValue = DateTime.Now.ToString("yyyy-MM-dd");
                    status.StatusValue = DateTime.Now.ToLongDateString();
                    ProfileModel.Update();
                    LoggerHelper.LogZICMonitor("成功发送管理信息每日汇报");
                }

            }
        }

        public void SendMonthlyReportSMS()
        {
            DateTime monthlyReportTime = DateTime.Today + new TimeSpan(17, 30, 0);
            DateTime currentMonthlyReportTime = new DateTime(2000, 1, 1);

            if ((DateTime.Today.AddDays(1).Month != DateTime.Today.Month) && (DateTime.Now.Subtract(monthlyReportTime).TotalMinutes > 0))
            {
                GeneralStatu status = ProfileModel.GetGeneralStatus("月度报告");

                if (status.StatusValue != null)
                {
                    CultureInfo culture = CultureInfo.CreateSpecificCulture("zh-CHS");
                    if (!DateTime.TryParse(status.StatusValue,
                                             culture,
                                             DateTimeStyles.None,
                                            out currentMonthlyReportTime))
                    {
                        throw new Exception(string.Format("[SendMonthlyReportSMS] Can't covnert datetime {0}", status.StatusValue));
                    }

                }
                if (status.StatusValue == null || DateTime.Now.Subtract(currentMonthlyReportTime).TotalDays >= 20)
                {
                    CCF20Entities ccf20 = new CCF20Entities();
                    SMSTest smsTest = new SMSTest(ccf20);
                    smsTest.MonthlyReportSMS();
                    status.StatusValue = DateTime.Now.ToLongDateString();
                    ProfileModel.Update();

                }
            }

        }
    }
}
